﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OPM.Class;
using OPM.Library.Models;
using OPM.Models;

namespace OPM.Controllers
{
    public class GroupListController : Controller
    {
        //แก้ไข
        public ActionResult EditCase(string id)
        {
            var editCase = WSO.GetCase(U.Token, id);
            // หลังจากเรียก GetCase เสร็จแล้ว ก็เรียก
            // WSO.GetCaseOrganization("77FA760D3BB845139248CEE480E6AAF2", "099AAC5FBF4141C2905F1C1688FBBF68"); //เพื่อดูว่าเรื่องนี้มีหน่วยงานใดเกี่ยวข้องบ้าง

            var sl = new SL();
            SelectList severities = sl.GetSeverity();
            SelectList listPriorities = sl.GetPriority();
            SelectList secrets = sl.GetSecret();
            ViewBag.severities = severities;
            ViewBag.listPriorities = listPriorities;
            ViewBag.secrets = secrets;
            ViewBag.SuccessResult = TempData["SuccessResult"];
            ViewBag.ErrorResult = TempData["ErrorResult"];


            return View(editCase);
        }

        //แก้ไข
        [HttpPost]
        public ActionResult EditCase(FormCollection f, GetCase model,
            string[] file_content = null, string[] file_description = null, string[] doc_type_id = null,
            string[] doc_no = null, string[] doc_date = null, string[] doc_ref_no = null,
            string[] doc_ref_date = null, string[] file_name = null, string[] doc_type = null)
        {
            // Prepare Data  
            model.list_case_org_owner = (f["list_case_org_owner"] ?? "").Split(',').Select(o => new CaseOrgOwner { org_id = o }).ToList();
            model.channel_outgoing_id = model.channel_outgoing_id ?? "";
            model.summary = model.summary ?? "";
            model.case_area = model.case_area ?? "";
            model.latitude = model.latitude ?? "";
            model.longitude = model.longitude ?? "";
            model.terminal_type_id = model.terminal_type_id ?? "";
            model.org_master_id = model.list_case_org_owner.Select(o => o.org_id).FirstOrDefault();
            string result = WSO.EditCase(model);

            var case_id_result = Util.TryCutString(result, "|", 1).Replace("\"", "");

            if (!string.IsNullOrWhiteSpace(case_id_result) && file_content != null && file_content.Any())
            {
                for (int i = 0; i < file_content.Length; i++)
                {
                    var file_content_type_ = file_content[i].Split(',')[0];
                    var file_content_base64_ = file_content[i].Split(',')[1];

                    var token = U.Token;
                    var file_name_ = file_name[i];
                    var file_content_ = file_content_base64_;
                    var file_description_ = file_description[i];
                    var doc_type_id_ = doc_type_id[i];
                    var doc_type_ = doc_type[i];
                    var doc_no_ = doc_no[i];
                    var doc_date_ = Util.ConvertDateTimeToWebService(doc_date[i]);
                    var doc_ref_no_ = doc_ref_no[i];
                    var doc_ref_date_ = Util.ConvertDateTimeToWebService(doc_ref_date[i]);
                    result += "รหัสเอกสารแนบ " + (i + 1) + ": " + WSO.InformAttachment(token, case_id_result, file_name_, file_content_, file_description_, doc_type_id_, doc_type_, doc_no_, doc_date_, doc_ref_no_, doc_ref_date_);
                }
            }


            TempData["SuccessResult"] = result;
            TempData["ErrorResult"] = string.IsNullOrWhiteSpace(case_id_result) ? result : null;

            return RedirectToAction("EditCase", new { id = model.case_id });
        }

        //สำเนาเปิดเรื่องใหม่
        [HttpGet]
        public ActionResult ViewCase(string id, string status)
        {
            //var editCase = WSO.GetCase("77FA760D3BB845139248CEE480E6AAF2", "099AAC5FBF4141C2905F1C1688FBBF68");
            
            try
            {
                var editCase = WSO.GetCase(U.Token, id);

                ViewBag.caseid = id;
                var getcase = new List<GetCase>();

                getcase.Add(new OPM.Models.GetCase
                {
                    ref_code = editCase.ref_code,
                    terminal_type_id = editCase.terminal_type_id,
                    date_closed = editCase.date_closed,
                    summary_result = editCase.summary_result,
                    summary_result_by = editCase.summary_result_by,
                    summary_result_by_text = editCase.summary_result_by_text,
                    channel_incoming_id = editCase.channel_incoming_id,
                    call_backnull = editCase.call_backnull,
                    channel_outgoing_id = editCase.channel_outgoing_id,
                    customer = editCase.customer,
                    org_text = editCase.org_text,
                    case_org_status_text = editCase.case_org_status_text,
                    case_org_summary_result = editCase.case_org_summary_result,
                    detail = editCase.detail,
                    date_occurrenced_from = editCase.date_occurrenced_from,
                    date_occurrenced_to = editCase.date_occurrenced_to,
                    case_area = editCase.case_area,
                    case_code = editCase.case_code,
                    case_id = editCase.case_id,
                    objective_id = editCase.objective_id,
                    objective_text = editCase.objective_text,
                    type_id = editCase.type_id,
                    type_text = editCase.type_text,
                    status_id = editCase.status_id,
                    status_text = editCase.status_text,
                    summary = editCase.summary,
                    defendant = editCase.defendant,
                    date_opened = editCase.date_opened,
                    time_occurrenced = editCase.time_occurrenced,
                    country_id = editCase.country_id,
                    subdistrict_id = editCase.subdistrict_id,
                    subdistrict_text = editCase.subdistrict_text,
                    district_id = editCase.district_id,
                    district_text = editCase.district_text,
                    province_id = editCase.province_id,
                    province_text = editCase.province_text,
                    used_inform_with = editCase.used_inform_with,
                    postcode = editCase.postcode,
                    latitude = editCase.latitude,
                    longitude = editCase.longitude,
                    case_value = editCase.case_value,
                    severity_id = editCase.severity_text,
                    severity_text = editCase.severity_text,
                    priority_id = editCase.priority_id,
                    priority_text = editCase.priority_text,
                    secret_id = editCase.secret_id,
                    secret_text = editCase.secret_text,
                    is_secret = editCase.is_secret,
                   // is_in_court_text = editCase.is_in_court_text,
                    remark = editCase.remark,
                    tq_key = editCase.tq_key,
                    created = editCase.created,
                    created_by = editCase.created_by,
                    created_by_text = editCase.created_by_text,
                    updated = editCase.updated,
                    updated_by = editCase.updated_by,
                    updated_by_text = editCase.updated_by_text,
                    list_case_org_owner = editCase.list_case_org_owner


                });

                string org_id = "";

                if (status == null)
                {
                    org_id = "";
                }
                else
                {
                    org_id = status;
                }

                var operating = WSO.GetOperatings(U.Token, id, org_id, 0, 10);
                var customerProfile = WSO.GetCaseCustomerProfile(U.Token, id);
                var timeline_header = WSO.GetTimelineHeader(U.Token, id, "A", 0, 1000);
   

                var org = WSL.GetOrganization("");
                LovOperatingStatus();
                ViewBag.viewcase = getcase;
                ViewBag.timeline_header = timeline_header;

                ViewBag.operating = operating;
                ViewBag.cusPro = customerProfile;

                return View(org);
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index", "Timeline");
            }
            return View("");
        }

       
        //ประสานงาน
        public ActionResult ContactAccount()
        {
            var model = new ContactAccount();
            model.date_opened = DateTime.Now;
            return View(model);
        }

        [HttpPost]
        public ActionResult ContactAccount(ContactAccount model, string org_id = null, string cont_id = null,
            string type_id = null, string status = null, string case_id = null,
            string[] file_content = null, string[] file_description = null, string[] doc_type_id = null,
            string[] doc_no = null, string[] doc_date = null, string[] doc_ref_no = null,
            string[] doc_ref_date = null, string[] file_name = null, string[] doc_type = null)
        {
            // type
            // status
            // org_id
            // cont_id
            try
            {
                string type = model.account_type;
                string remark = model.summary;
                string detail = model.detail;
                string priority_id = model.priority_id;
                string severity_id = model.severity_id;
                string secret_id = model.secret_id;
                if (string.IsNullOrWhiteSpace(priority_id) || string.IsNullOrWhiteSpace(severity_id) ||
                    string.IsNullOrWhiteSpace(secret_id))
                {

                    ViewBag.ErrorResult = "กรุณากรอกข้อมูลให้ครบถ้วน";
                    return View(model);
                }

                string result = WSO.AddOperating(U.Token, case_id, type, status, org_id, "",
                    Util.ConvertDateTimeToWebService(DateTime.Now),
                    "", "", detail, severity_id, priority_id, secret_id);

                var operating_id_result = Util.TryCutString(result, ":", 1).Replace("\"", "");

                //var operating = WSO.GetOperating(U.Token, operating_id_result);

                if (!string.IsNullOrWhiteSpace(operating_id_result) && file_content != null && file_content.Any())
                {
                    for (int i = 0; i < file_content.Length; i++)
                    {
                        var file_content_type_ = file_content[i].Split(',')[0];
                        var file_content_base64_ = file_content[i].Split(',')[1];

                        var token = U.Token;
                        var file_name_ = file_name[i];
                        var file_content_ = file_content_base64_;
                        var file_description_ = file_description[i];
                        var doc_type_id_ = doc_type_id[i];
                        var doc_type_ = doc_type[i];
                        var doc_no_ = doc_no[i];
                        var doc_date_ = Util.ConvertDateTimeToWebService(doc_date[i]);
                        var doc_ref_no_ = doc_ref_no[i];
                        var doc_ref_date_ = Util.ConvertDateTimeToWebService(doc_ref_date[i]);
                        result += "รหัสเอกสารแนบ " + (i + 1) + ": " +
                                  WSO.OperatingAttachment(token,
                                      case_id,
                                      operating_id_result,
                                      file_name_,
                                      file_content_,
                                      file_description_,
                                      doc_type_id_,
                                      doc_type_, doc_no_,
                                      doc_date_, doc_ref_no_,
                                      doc_ref_date_);
                    }
                }


            }
            catch (Exception ex)
            {
                ViewBag.ErrorResult = ex.Message;
                return View(model);
            }

            return RedirectToAction("Index", "PopupResult");

        }

        public ActionResult ViewCaseDetail()
        {
            var model = new ContactAccount();
            model.date_opened = DateTime.Now;
            return View(model);
        }

        //รายงานผล
        [HttpPost]
        public ActionResult ViewCaseDetail(ContactAccount model, string org_id = null, string cont_id = null,
            string type_id = null, string status = null, string case_id = null,
            string[] file_content = null, string[] file_description = null, string[] doc_type_id = null,
            string[] doc_no = null, string[] doc_date = null, string[] doc_ref_no = null,
            string[] doc_ref_date = null, string[] file_name = null, string[] doc_type = null)
        {
            try
            {
                string type = model.type;
                string remark = model.summary;
                string detail = model.detail;
                string priority_id = model.priority_id;
                string severity_id = model.severity_id;
                string secret_id = model.secret_id;

                string result = WSO.AddOperating(U.Token, case_id, type, status, "", "",
                    Util.ConvertDateTimeToWebService(DateTime.Now),
                    "", "", detail, severity_id, priority_id, secret_id);

                var operating_id_result = Util.TryCutString(result, ":", 1).Replace("\"", "");

                //var operating = WSO.GetOperating(U.Token, operating_id_result);

                if (!string.IsNullOrWhiteSpace(operating_id_result) && file_content != null && file_content.Any())
                {
                    for (int i = 0; i < file_content.Length; i++)
                    {
                        var file_content_type_ = file_content[i].Split(',')[0];
                        var file_content_base64_ = file_content[i].Split(',')[1];

                        var token = U.Token;
                        var file_name_ = file_name[i];
                        var file_content_ = file_content_base64_;
                        var file_description_ = file_description[i];
                        var doc_type_id_ = doc_type_id[i];
                        var doc_type_ = doc_type[i];
                        var doc_no_ = doc_no[i];
                        var doc_date_ = Util.ConvertDateTimeToWebService(doc_date[i]);
                        var doc_ref_no_ = doc_ref_no[i];
                        var doc_ref_date_ = Util.ConvertDateTimeToWebService(doc_ref_date[i]);
                        result += "รหัสเอกสารแนบ " + (i + 1) + ": " +
                                  WSO.OperatingAttachment(token,
                                      case_id,
                                      operating_id_result,
                                      file_name_,
                                      file_content_,
                                      file_description_,
                                      doc_type_id_,
                                      doc_type_, doc_no_,
                                      doc_date_, doc_ref_no_,
                                      doc_ref_date_);
                    }
                }

            }
            catch (Exception ex)
            {
                ViewBag.ErrorResult = ex.Message;
                return View(model);
            }

            return RedirectToAction("Index", "PopupResult");

        }

        //ประชาชนติดตาม

        public ActionResult DuplicateCase()
        {

            Secret();
            Severity();
            Priority();
            LovCaseType();
            LovOperatingStatus();
            LovChannelIn();
            LovContactObj();

            var model = new ContactAccount();
            model.date_opened = DateTime.Now;
            return View(model);

        }

        [HttpPost]
        public ActionResult DuplicateCase(FormCollection f, ContactAccount model, 
            //receipt 
            string cont_id = null,
            string type_id = null, 
            string status = null,
            string case_id = null,
            string org_id = null, 
            string owner_id = null,            
            string date_open = null, 
            string hour = null,
            string minute = null, 
            string cont_cont_id = null,
            string cont_org_id = null, 
            string lovchannelin = null, // ช่องทางการติดต่อ
            string lovobject = null, // วัตถุประสงค์ในการติดต่อ
            string cont_is_secret = null, // ผู้ติดต่อ 
            string cont_type = null, // ผู้ติดต่อ  
            string cont_country_id = null, // ผู้ติดต่อ  
            string cont_gender_id = null, // ผู้ติดต่อ  
            string cont_title = null, // ผู้ติดต่อ  
            string cont_firstname = null, // ผู้ติดต่อ  
            string cont_lastname = null, // ผู้ติดต่อ 
            string cont_citizen_id = null, // ผู้ติดต่อ  
            string cont_address = null, // ผู้ติดต่อ    
            string cont_province_id = null, // ผู้ติดต่อ   
            string cont_subdistrict_id = null,
            string cont_district_id = null,
            string cont_postcode = null,

            string cont_number = null,
            string cont_is_defective = null, 
            string cont_birthday = null,

            string cont_tel_all = null,
            string cont_mobile_all = null,
            string cont_email_send_all = null,
            string cont_remark = null,
            string cont_contact_detail = null,

              
            string[] file_content = null, string[] file_description = null, string[] doc_type_id = null,
            string[] doc_no = null, string[] doc_date = null, string[] doc_ref_no = null,
            string[] doc_ref_date = null, string[] file_name = null, string[] doc_type = null
            )
        {
            var x = UtilWeb.GetParamWithValueMvcFormCollection(f);
            string type = model.type;
            string remark = model.summary;
            string detail = model.detail;
            string priority_id = model.priority_id;
            string severity_id = model.severity_id;
            string secret_id = model.secret_id;
            string date_opened = Util.ConvertDateTimeToWebService(date_open + " " + hour + ":" + minute);

            try
            {
                #region
                Secret();
                Severity();
                Priority();
                LovCaseType();
                LovOperatingStatus();
                LovChannelIn();
                LovContactObj();
                #endregion

                string result = WSO.AddOperating(U.Token,
                    case_id,
                    type,
                    status,
                    org_id,
                    owner_id,
                    date_opened,
                    "",
                    remark,
                    detail,
                    severity_id,
                    priority_id,
                    secret_id);

                var operating_id_result = Util.TryCutString(result, ":", 1).Replace("\"", "");

                //var operating = WSO.GetOperating(U.Token, operating_id_result);
               var addContactResult = WSO.AddContact(U.Token,
                    case_id,
                    lovchannelin,
                    lovobject,
                    type,
                    status,
                    date_opened,
                    "",
                    "",
                    detail,
                    cont_is_secret,
                    "",
                    cont_type,
                    cont_gender_id,
                    cont_title,
                    cont_firstname,
                    cont_lastname,
                    cont_citizen_id,
                    cont_contact_detail,
                    cont_country_id,
                    cont_address,
                    cont_subdistrict_id,
                    cont_district_id,
                    cont_province_id,
                    cont_postcode,
                    cont_birthday,
                    cont_remark,
                    cont_is_defective,
                    Util.ConvertToInt(cont_number),
                    "",
                    severity_id,
                    priority_id,
                    secret_id
                    );

                #region attach file
                if (!string.IsNullOrWhiteSpace(operating_id_result) && file_content != null && file_content.Any())
                {
                    for (int i = 0; i < file_content.Length; i++)
                    {
                        var file_content_type_ = file_content[i].Split(',')[0];
                        var file_content_base64_ = file_content[i].Split(',')[1];

                        var token = U.Token;
                        var file_name_ = file_name[i];
                        var file_content_ = file_content_base64_;
                        var file_description_ = file_description[i];
                        var doc_type_id_ = doc_type_id[i];
                        var doc_type_ = doc_type[i];
                        var doc_no_ = doc_no[i];
                        var doc_date_ = Util.ConvertDateTimeToWebService(doc_date[i]);
                        var doc_ref_no_ = doc_ref_no[i];
                        var doc_ref_date_ = Util.ConvertDateTimeToWebService(doc_ref_date[i]);
                        result += "รหัสเอกสารแนบ " + (i + 1) + ": " +
                                  WSO.OperatingAttachment(token,
                                      case_id,
                                      operating_id_result,
                                      file_name_,
                                      file_content_,
                                      file_description_,
                                      doc_type_id_,
                                      doc_type_, doc_no_,
                                      doc_date_, doc_ref_no_,
                                      doc_ref_date_);
                    }
                }
                #endregion

            }
            catch (Exception ex)
            {
                ViewBag.ErrorResult = ex.Message;
                return View(model);
            }

            return RedirectToAction("Index", "PopupResult");

        }

        //ประเภทเรื่องร้องเรียน
        public void LovCaseType()
        {
            var listOfCaseType = WSL.GetCaseType("");

            ViewBag.listOfCaseType = new SelectList(listOfCaseType, "VAL", "TEXT");
            //   return View(listOfCaseType);
        }

        public void LovOperatingStatus()
        {
            var listOfOperatingStatus = WSL.GetOperatingStatus();
            ViewBag.listOfOperatingStatus = new SelectList(listOfOperatingStatus, "VAL", "TEXT");
            //return View(listOfOperatingStatus);
        }

        public ActionResult LovSearchCustomer(string id)
        {
            var listOfSearchContact = WSO.SearchCustomerProfiles(U.Token, "", 0, 10);
            ViewBag.CaseId = id;
            return View(listOfSearchContact);
        }

        public ActionResult PopupAddCustomer(string case_id, string provinceId, string DistrictId, string SubDistrictId = null)
        {
            ViewBag.Caseid = case_id;
            LovGetCountry();
            GetGender();
            LovGetCountry();
            GetProvinces();
            GetDistricts(provinceId);
            GetSubDistricts(DistrictId);
            return View();
        }

        [HttpGet]
        public JsonResult AddCustomer(string id, string cust_type, string cust_gender_id, string cust_title,
                string cust_firstname, string cust_lastname, string cust_citizen_id, string cust_contact_detail, string cust_country_id,
                int cust_number, string cust_address, string cust_subdistrict_id, string cust_district_id, string cust_province_id,
                string cust_postcode, string cust_birthday, string cust_remark, string cust_is_defective, string cust_is_public)
        {
            try
            {
                var result = WSO.AddCustomer(U.Token, id, cust_type, cust_gender_id, cust_title,
                    cust_firstname, cust_lastname, cust_citizen_id, cust_contact_detail, cust_country_id,
                    cust_number, cust_address, cust_subdistrict_id, cust_district_id, cust_province_id,
                    cust_postcode, cust_birthday, cust_remark, cust_is_defective, cust_is_public);
            }
            catch (Exception ex)
            {
                return Json("Error", JsonRequestBehavior.AllowGet);

            }
            return Json("Success", JsonRequestBehavior.AllowGet);

        }

        public class SaveResult
        {
            public string result_text { get; set; }
        }

        public ActionResult Profile()
        {
            var profiles = WSO.GetOfficerProfile(U.Token, U.officer_id);
            var profileModel = new List<OfficerProfile>();

            profileModel.Add(new OfficerProfile
            {

                //id = profiles.id,
                //ref_id = profiles.ref_id,
                //username = profiles.username,
                //name = profiles.name,
                //position = profiles.position,
                //org_id = profiles.org_id,
                //org_text = profiles.org_text,
                //contact_details = profiles.contact_details,
                //image = profiles.image
            });


            ViewBag.profile = profileModel;

            return View();
        }

        public ActionResult PopupGetOperating(string id)
        {
            try
            {
                var getContact = WSO.GetContact(U.Token, id);

                var contactModel = new List<GetContact>();

                contactModel.Add(new GetContact
               {
                   id = getContact.id,
                   contact_code = getContact.contact_code,
                   objective_id = getContact.objective_id,
                   objective_text = getContact.objective_text,
                   contact_date = getContact.contact_date,
                   channel_id = getContact.channel_id,
                   channel_text = getContact.channel_text,
                   account_id = getContact.account_id,
                   account_name = getContact.account_name,
                   detail = getContact.detail,
                   tq_key = getContact.tq_key,
                   is_public = getContact._is_public,
                   created_by = getContact.created_by,
                   created_by_text = getContact.created_by_text
               });


                var operating = WSO.GetOperating(U.Token, id);
                var ModelOperating = new List<Operating>();

                ModelOperating.Add(new Operating
                {
                    operating_type_id = operating.operating_type_id,
                    status_id = operating.status_id,
                    date_closed = operating.date_closed,
                    operating_code = operating.operating_code,
                    severity_id = operating.severity_id,
                    priority_id = operating.priority_id,
                    secret_id = operating.secret_id,
                    operating_type_text = operating.operating_type_text,
                    status_text = operating.status_text,
                    org_text = operating.org_text,
                    summary = operating.summary,
                    attachments = operating.attachments,
                    severity_text = operating.severity_text,
                    secret_text = operating.secret_text,
                    priority_text = operating.priority_text,
                    created_by_text = operating.created_by_text,
                    date_opened = operating.date_opened
                });


                ViewBag.operating = ModelOperating;
                ViewBag.contactModel = contactModel;
            }catch(Exception ex){
                return RedirectToAction("Index", "Timeline");
            }
            return View();
        }

        [HttpGet]
        public ActionResult ContactDetail(string account_id)
        {

            var account = WSO.GetContactAccount(U.Token, account_id);
            var contact_account = new List<ContactAccount>();

            if (account != null)
            {
                contact_account.Add(new ContactAccount
                {
                    list_account_detail = account.list_account_detail,
                    firstname_th = account.firstname_th,
                    lastname_th = account.lastname_th,
                    gender_id = account.gender_id,
                    gender_text = account.gender_text,
                    citizen_id = account.citizen_id,
                    country_id = account.country_id,
                    country_name = account.country_name,
                    address = account.address,
                    subdistrict_text = account.subdistrict_text,
                    district_text = account.district_text,
                    province_text = account.province_text,
                    postcode = account.postcode,
                    remark = account.remark
                    
                });


                var contactAccountCase = WSO.GetContactAccountCases(U.Token, account_id, 0, 10);

                var contact_account_case = new List<ContactAccountCases>();

                foreach(var ac_case in contactAccountCase){
                contact_account_case.Add(new ContactAccountCases
                {
                    case_code = ac_case.case_code,
                    objective_text = ac_case.objective_text,
                    type_text = ac_case.type_text,
                    summary = ac_case.summary,
                    status_text = ac_case.status_text
                });
            }

                ViewBag.AccountCase = contact_account_case;

                return View(contact_account);
            }
            else
            {

                return View("ViewCase", "GroupList");
            }
        }

        [HttpGet]
        public JsonResult AddOperating(string operation_type, string operating_status,
                                        string detail, string severity_id, string secret_id,
                                        string priority_id, string case_id, string date_opened,
                                        string summary)
        {
            string ret = WSO.AddOperating(U.Token, case_id, operation_type, operating_status, "", ""
              , Util.ConvertDateTimeToWebService(DateTime.Now), "", summary, detail, severity_id, priority_id, secret_id);



            return Json("", JsonRequestBehavior.AllowGet);
        }


        
        public ActionResult EditContactAccount(string account_id)
        {
            var editcontact = WSO.GetContactAccount(U.Token, account_id);

            return View(editcontact);
        }


        [HttpPost]
        public ActionResult EditContactAccount(SearchContact model)
        {
            // var editcontact = WSO.EditContactAccount(U.Token, account_id);
            return View();
        }

        public ActionResult CustomerLog(string account_id)
        {
            var log = WSO.GetCustomerProfileLogs(U.Token, account_id, 0, 10);
            return View(log);
        }

        //ระดับชั้นความสำคัญ
        public void Priority()
        {
            var listOfPriority = WSL.GetPriority();
            ViewBag.listOfPriority = new SelectList(listOfPriority, "VAL", "TEXT");
        }

        //ระดับชั้นความลับ 
        public void Secret()
        {
            var listOfSecret = WSL.GetSecret();
            ViewBag.listOfSecret = new SelectList(listOfSecret, "VAL", "TEXT");
        }

        //ระดับชั้นความเร่งด่วน 
        public void Severity()
        {
            var listOfSeverity = WSL.GetSeverity();
            ViewBag.listOfSeverity = new SelectList(listOfSeverity, "VAL", "TEXT");
        }

        public void GetGender()
        {
            var listOfGender = WSL.GetGender();
            ViewBag.listOfGender = new SelectList(listOfGender, "VAL", "TEXT");
        }

        //วัตถุประสงค์การติดต่อ
        public ActionResult LovContactObj()
        {
            var listContaceObj = WSL.GetContactObjective("");
            return View(listContaceObj);
        }


        public ActionResult RootContactObj(string id)
        {
            var listNode = "";
            var listNodeContaceObj = WSL.GetContactObjective(id);

            var query_node_obj = (from x in listNodeContaceObj
                                  where x.ref_val == id
                                  select x.val).FirstOrDefault();
            if (query_node_obj == null)
            {
                listNode = "";
            }
            else
            {
                listNode = query_node_obj;

            }
            return Json(listNode, JsonRequestBehavior.AllowGet);
        }
        // ช่องทางการติดต่อ
        public ActionResult LovChannelIn()
        {
            var listChanel = WSL.GetChannelIn("", U.org_id);
            return View(listChanel);
        }

        public ActionResult RootChannel(string id)
        {
            string rootNode_Cha = "";
            var listNodeChanel = WSL.GetChannelIn(id, U.org_id);

            var query_node_cha = (from x in listNodeChanel
                                  where x.ref_val == id
                                  select x.val).FirstOrDefault();

            if (query_node_cha == null)
            {
                rootNode_Cha = "";
            }
            else
            {
                rootNode_Cha = query_node_cha;

            }


            return Json(rootNode_Cha, JsonRequestBehavior.AllowGet);
        }

        //ประเภทการปฏิบัติงาน
        public ActionResult OperatingType()
        {
            var listOfOperatingType = WSL.GetOperatingType("");
            return View(listOfOperatingType);
        }

        //สถานะการปฏิบัติงาน
        public ActionResult OperatingStatus()
        {
            var listOfOperatingStatus = WSL.GetOperatingStatus();
            //ViewBag.listOfOperatingStatus = listOfOperatingStatus;
            return View(listOfOperatingStatus);
        }


        public ActionResult EditOperating(string case_id)
        {
            Priority();
            Secret();
            Severity();
            var operating = WSO.GetOperating(U.Token, case_id);
            return View(operating);
        }

        [HttpPost]
        public ActionResult EditOperating(GetOperating model, string org_id = null, string cont_id = null,
            string status = null, string case_id = null,
            string[] file_content = null, string[] file_description = null, string[] doc_type_id = null,
            string[] doc_no = null, string[] doc_date = null, string[] doc_ref_no = null,
            string[] doc_ref_date = null, string[] file_name = null, string[] doc_type = null)
        {
            Priority();
            Secret();
            Severity();

            try
            {
                string operating_id = model.id;
                string type_id = model.operating_type_id;
                string status_id = model.status_id;
                string terminal_org_id = model.org_id;
                string date_opened = Util.ConvertDateTimeToWebService(model.date_opened);
                string date_closed = Util.ConvertDateTimeToWebService(model.date_closed);

                var editOperating = WSO.EditOperating(U.Token, operating_id, type_id, status_id, terminal_org_id, "",
                   date_opened, date_closed, model.summary, "", model.severity_id, model.priority_id, model.secret_id);


                var operating_id_result = Util.TryCutString(editOperating, ":", 1).Replace("\"", "");


                if (!string.IsNullOrWhiteSpace(operating_id_result) && file_content != null && file_content.Any())
                {
                    for (int i = 0; i < file_content.Length; i++)
                    {
                        var file_content_type_ = file_content[i].Split(',')[0];
                        var file_content_base64_ = file_content[i].Split(',')[1];

                        var token = U.Token;
                        var file_name_ = file_name[i];
                        var file_content_ = file_content_base64_;
                        var file_description_ = file_description[i];
                        var doc_type_id_ = doc_type_id[i];
                        var doc_type_ = doc_type[i];
                        var doc_no_ = doc_no[i];
                        var doc_date_ = Util.ConvertDateTimeToWebService(doc_date[i]);
                        var doc_ref_no_ = doc_ref_no[i];
                        var doc_ref_date_ = Util.ConvertDateTimeToWebService(doc_ref_date[i]);
                        editOperating += "รหัสเอกสารแนบ " + (i + 1) + ": " +
                                  WSO.OperatingAttachment(token,
                                      case_id,
                                      operating_id_result,
                                      file_name_,
                                      file_content_,
                                      file_description_,
                                      doc_type_id_,
                                      doc_type_, doc_no_,
                                      doc_date_, doc_ref_no_,
                                      doc_ref_date_);
                    }
                }

            }catch(Exception ex){
                ViewBag.ErrorResult = ex.Message;
                return View(model);
            }

            return RedirectToAction("Index", "PopupResult");
        }

        //ผู้รับ
        public void CaseOrganization(string token_id, string case_id)
        {
            var caseOganiz = WSO.GetCaseOrganization(U.Token, case_id);

        }

        //เจ้าหน้าที่
        public void GetCaseOfficer(string case_id)
        {
            var caseOfficer = WSO.GetCaseOfficer(U.Token, case_id, U.org_id, 0, 10);
        }

        public void LovGetCountry()
        {
            var listOfCountry = WSL.GetCountry();
            ViewBag.listOfCountry = new SelectList(listOfCountry, "VAL", "TEXT");
        }

        public void GetProvinces(string selectedProvinceId = null)
        {
            var listOfProvinces = WSL.GetProvinces();
            var listOfProvincesSl = new SelectList(listOfProvinces, "ID", "NAME");
            var selectedProvinceSl = listOfProvincesSl.FirstOrDefault(o => o.Value == selectedProvinceId);
            if (selectedProvinceSl != null) { selectedProvinceSl.Selected = true; }
            ViewBag.listOfProvinces = listOfProvincesSl;
        }

        public void GetDistricts(string provinceId, string selectedDistricteId = null)
        {
            var listOfDistricts = WSL.GetDistricts(provinceId);
            var listOfDistrictsSl = new SelectList(listOfDistricts, "ID", "NAME");
            var selectedDistrictSl = listOfDistrictsSl.FirstOrDefault(o => o.Value == selectedDistricteId);
            if (selectedDistrictSl != null) { selectedDistrictSl.Selected = true; }
            ViewBag.listOfDistricts = listOfDistrictsSl;
        }

        public void GetSubDistricts(string DistrictId, string selectedSubDistricteId = null)
        {
            var listOfSubDistricts = WSL.GetSubDistricts(DistrictId);
            var listSubOfDistrictsSl = new SelectList(listOfSubDistricts, "ID", "NAME");
            var selectedSubDistrictSl = listSubOfDistrictsSl.FirstOrDefault(o => o.Value == selectedSubDistricteId);
            if (selectedSubDistrictSl != null) { selectedSubDistrictSl.Selected = true; }
            ViewBag.listOfSubDistricts = listSubOfDistrictsSl;
        }
        public ActionResult GetDistrictsJson(string provinceId)
        {
            var listOfDistricts = WSL.GetDistricts(provinceId);
            return Json(listOfDistricts, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetSubDistrictsJson(string districtId)
        {
            var listOfSubDistricts = WSL.GetSubDistricts(districtId);
            return Json(listOfSubDistricts, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SelectTerminal()
        {
            return View();
        }
    }
}
